package com.seveneight.baijiesteward.utils;


import android.text.TextUtils;

import org.json.JSONObject;

import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;

/**
 * Created by user1 on 2018/3/31.
 */

public class JsonUtils {

    /**
     * 对json的键值进行首字母排序
     *
     * @param json
     * @return
     */
    public static String sort(JSONObject json) {
        try {
            json.put("FuckHacker", MD5Parse.md5Time());
        } catch (Exception ex) {

        }
        Iterator<String> iteratorKeys = json.keys();
        SortedMap map = new TreeMap();
        StringBuilder parseJson = new StringBuilder();
        while (iteratorKeys.hasNext()) {
            String key = iteratorKeys.next().toString();
            String value = json.optString(key);
            if (!TextUtils.isEmpty(value)) {
                map.put(key, value);
            }
        }
        SortedMap<String, String> sort = new TreeMap<String, String>(map);
        Set<Map.Entry<String, String>> entry1 = sort.entrySet();
        Iterator<Map.Entry<String, String>> it = entry1.iterator();
        while (it.hasNext()) {
            Map.Entry<String, String> entry = it.next();
            parseJson.append(entry.getKey() + "=" + entry.getValue() + "&");
        }
        LogUtil.d("排序后的json:" + parseJson.toString());
        return parseJson.substring(0,parseJson.length()-1);
    }


}
